from cameralib import *
from time import time, sleep
from Tkinter import *
from ImageTk import PhotoImage
import sys
import Image
from time import time
import tkFont

def main():
  webcam = Webcam(resolution='lo')
  root = Tk()
  # w, h = 640, 480
  # root.overrideredirect(1)
  # root.geometry("%dx%d+100+100" % (w,h))
  # root.focus_set()
  root.overrideredirect(1)
  root.geometry("%dx%d+0+0" % (root.winfo_screenwidth(), root.winfo_screenheight()))
  root.focus_set()
  root.bind('<Escape>', lambda e: root.quit())
  app = ThreeColorDemo(root, webcam)
  app.mainloop()
  del webcam
  
class ThreeColorDemo(Frame):

  def __init__(self, root, webcam, w=None, h=None):
  
    if not w or not h:
      self.width = root.winfo_screenwidth()
      self.height = root.winfo_screenheight()
    else:
      self.width, self.height = w, h
    self.stream = webcam.stream(format='numpy')
    
    Frame.__init__(self, root, width=self.width, height=self.height, background="#000000")
    self.grid()
    self.canvas = Canvas(self, width=self.width, height=self.height, background="#000000")
    self.canvas.grid()
    self.canvas.bind('<Button-1>', lambda e: self.z_order_displays(True))
    
    self.displays = dict() # display name -> image
    self.display_sequence = []
    self.build_displays()
    self.cycles = 0
    self.z_order_displays()
    self.render_loop()
    self.after(1000, self.animate, 'b', 100)

  def build_displays(self):
    displays = self.displays
    canvas = self.canvas
    displays['original'] = canvas.create_image(100, 100, anchor=NW, tag='displays')
    displays['r'] = canvas.create_image(200,200, anchor=NW, tag='displays')
    displays['g'] = canvas.create_image(300, 300, anchor=NW, tag='displays')
    displays['b'] = canvas.create_image(400, 400, anchor=NW, tag='displays')
    self.display_sequence = ['b', 'g', 'r', 'original']
    self.display_images = dict()
    
  def set_display(self, display, image):
    assert(isinstance(image, Image.Image))
    d = self.displays[display]
    self.display_images[display] = PhotoImage(image)
    self.canvas.itemconfigure(self.displays[display], image=self.display_images[display])
  
  def z_order_displays(self, rotate=False):
    if rotate:
      self.display_sequence.insert(0, self.display_sequence.pop())
      
    prev = None
    for item in [self.displays[x] for x in self.display_sequence]:
      if prev:
        self.canvas.tag_raise(item, prev)
      prev = item
    
  def render_loop(self):
    imarray = self.stream.next()
    self.set_display('original', convert_numpy_pil(imarray))
    self.cycles += 1
    i = self.cycles
    
    # color channels
    for color in 'rgb':
      channelarray = color_channel(imarray, color)
      self.set_display(color, convert_numpy_pil(channelarray))
    
    self.update()
    self.after(0, self.render_loop)

  def animate(self, display, totalsteps, step=0):
    id = self.displays[display]
    if step < totalsteps:
      self.canvas.move(id, 5, 0)
      self.after(5, self.animate, display, totalsteps, step+1)

if __name__ == '__main__':
  main()
  print "all done"